<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref, h } from 'vue'
import { ElMessage, ElMessageBox } from "element-plus";
import { VideoPlay, SwitchButton, Mic, FullScreen, CloseBold } from '@element-plus/icons-vue'
import VuePlayer from '@/components/player/VuePlayer.vue'
import { Camera } from '@/interface/home'
import { avRequest } from '@/api/gps/jt808/jt1078'
import { avControl } from '@/api/gps/jt808/jt1078'
import { gpsbus } from '@/utils/gps/event'
import { storeToRefs } from 'pinia'
import useDeviceStore from "@/store/gps/device";
import { createPopup } from "@/utils/gps/createPopup";
import Intercom from "@/components/gps-video/intercom"
import { jt1078AvsetAnalysis } from '@/utils/gps/format'
import {resolveNodeId} from "@/utils/gps/device";

const deviceStore = useDeviceStore()
const props = defineProps({
  fullScreen: {
    type: Boolean,
    default: false
  },
  cellCount: {
    type: Number,
    default: 4
  }
})

const { checkedDeviceList, checkedDeviceNodeId, checkedDeviceInfo, videoPageDisable } = storeToRefs(deviceStore)

const closeBtn = ref(0)
const cellCount = ref<number>(props.cellCount!)
const streamTypeAct = ref(1)

const videoRefs = ref<any[]>([])
// 播放列表的nodeId,此处为(c-id-channel)
const videoNodeIdList = ref<string[]>(new Array(36).fill(''))
// 设备数据 {nodeId: data}
const videoData = ref<{ [nodeId: string]: Camera }>({})
// 通道是否已满
const isVideoChannelFull = computed<boolean>(() => {
  return Object.keys(videoData.value).length === cellCount.value
})


onMounted(() => {
  gpsbus.on('insertVideo', insertVideo)
  gpsbus.on('removeVideo', videoDestroy)
})
onUnmounted(() => {
  gpsbus.off('insertVideo', insertVideo)
  gpsbus.off('removeVideo', videoDestroy)
})
/**
 * 新增视频
 * @param camera
 */
function insertVideo(camera: Camera) {
  videoPageDisable.value = false
  return new Promise((resolve, reject) => {
    console.log('新增视频', camera)
    const { nodeId, parentNodeId } = camera
    const resPid = resolveNodeId(parentNodeId)
    if (!nodeId) {
      reject()
      return
    }
    if (isVideoChannelFull.value) {
      if (!increaseChannel()) {
        gpsbus.emit('unSelect', nodeId)
        ElMessage.info('播放窗口已满')
        reject()
        return
      } else {
        setTimeout(() => {
          insertVideo(camera).then(() => {
            resolve('ok')
          }).catch(() => {
            reject()
          })
        }, 100)
        return
      }
    }
    if (!videoNodeIdList.value.includes(nodeId)) {
      ElMessage.info('正在创建连接。。。')
      closeBtn.value++
      // 计算应该放在第几个播放通道里
      const index = calculationChannel()
      if (index === 1000) {
        reject()
        return
      }
      camera.index = index
      videoNodeIdList.value[index] = nodeId
      videoData.value[nodeId] = camera
      videoRefs.value[index].init(({ play, fail, config }) => {
        avRequest({
          imei: resPid.id,
          channel: camera.channel,
          streamType: streamTypeAct.value,
          mediaType: 0
        }, config)
          .then((res) => {
            videoData.value[nodeId].playerUrl = res.data.streamUrl
            play(res.data.streamUrl2, res.data.heartKey)
            // play('ws://127.0.0.1:13333/video/' + res.data.heartKey + '?type=1', res.data.heartKey)
            closeBtn.value--
            resolve('ok')
          })
          .catch(() => {
            fail()
            reject()
          })
      }, true)
    }
  })
}

/**
 * 计算空余通道
 */
function calculationChannel(): number {
  const len = Object.keys(videoData.value).length
  for (let i = 0; i <= len; i++) {
    if (videoNodeIdList.value[i] === '') {
      return i
    }
  }
  return 1000
}

/**
 * 关闭单个窗口及销毁视频数据
 * @param nodeId
 */
function videoDestroy(nodeId: string) {
  if (!nodeId) return
  const { index, parentNodeId, channel } = videoData.value[nodeId]
  videoNodeIdList.value[index] = ''
  delete videoData.value[nodeId]
  videoRefs.value[index]?.closeVideoWindow()
  avControl(resolveNodeId(parentNodeId).id, channel)
}

/**
 * 移除摄像头选中
 * @param index 播放通道
 */
function removeVideo(index: number) {
  const nodeId = videoNodeIdList.value[index]
  gpsbus.emit('unSelect', nodeId)
}
/**
 * 关闭全部视频
 */
function closeVideoAll() {
  for (const video in videoData.value) {
    const { nodeId } = videoData.value[video]
    setTimeout(() => {
      gpsbus.emit('unSelect', nodeId)
    }, 10)
  }
  videoPageDisable.value = true
}

function openIntercom() {
  if (!checkedDeviceNodeId.value) {
    ElMessage.warning("请选择一台车")
    return
  }
  let a = checkedDeviceList.value[checkedDeviceNodeId.value]
  const channelNames = jt1078AvsetAnalysis(a.jt1078Avch, a.jt1078Avset)
  if (channelNames.length === 0) {
    return
  }
  let cl = channelNames[0]
  // for (let i = 0; i < channelNames.length; i++) {
  //   let cl = channelNames[i]
  // @ts-ignore
  ElMessageBox.confirm(
    `是否对{ ${checkedDeviceInfo.value.plateNo} ${cl.name} }发起双向对讲，请选择是否继续?`,
    '提示',
    {
      confirmButtonText: '继续',
      cancelButtonText: '取消',
      type: 'warning',
      center: true,
    }
  ).then(() => {
    createPopup({
      default: () => h(Intercom, {
        style: "",
        equipment: {
          imei: checkedDeviceNodeId.value,
          channel: 13,
          name: checkedDeviceInfo.value.plateNo
        }
      })
    }, {
      width: 300,
      height: 350,
      mask: false,
      drag: true
    })
  })
}

/**
 * 播放全部已选中的设备通道
 */
function playAll() {
  gpsbus.emit('checkedDeviceChannelAll', checkedDeviceNodeId.value)
}

const cellClass = (index: any): any => {
  switch (cellCount.value) {
    case 1:
      return ['cell-player-1']
    case 2:
      return ['cell-player-2']
    case 4:
      return ['cell-player-4']
    case 6:
      if (index === 1) {
        return ['cell-player-6-1']
      }
      if (index === 2) {
        return ['cell-player-6-2']
      }
      if (index === 3) {
        return ['cell-player-6-position']
      }
      return ['cell-player-6']
    case 9:
      return ['cell-player-9']
    case 16:
      return ['cell-player-16']
    case 25:
      return ['cell-player-25']
    case 36:
      return ['cell-player-36']
    default:
      break
  }
  return ['']
}

function increaseChannel() {
  switch (cellCount.value) {
    case 1:
      cellCount.value = 2
      break
    case 2:
      cellCount.value = 4
      break
    case 4:
      cellCount.value = 6
      break
    case 6:
      cellCount.value = 9
      break
    case 9:
      cellCount.value = 16
      break
    case 16:
      cellCount.value = 25
      break
    case 25:
      cellCount.value = 36
      break
    case 36:
      return false
    default:
      break
  }
  return true
}
defineExpose({
  insertVideo
})
</script>

<template>
  <div class="cell" :class="{ 'full_screen': props.fullScreen, 'disable': videoPageDisable}">
    <div class="cell-tool">
      <el-scrollbar>
        <el-radio-group v-model="cellCount" size="small" border class="grid-group">
          <el-radio-button :value="1">
            <template #default>
              <img src="../../../../assets/camera/window-item-1.png" class="grid" alt="" />
            </template>
          </el-radio-button>
          <el-radio-button :value="2">
            <template #default>
              <img src="../../../../assets/camera/window-item-2.png" class="grid" alt="" />
            </template>
          </el-radio-button>
          <el-radio-button :value="4">
            <template #default>
              <img src="../../../../assets/camera/window-item-4.png" class="grid" alt="" />
            </template>
          </el-radio-button>
          <el-radio-button :value="6">
            <template #default>
              <img src="../../../../assets/camera/window-item-6.png" class="grid" alt="" />
            </template>
          </el-radio-button>
          <el-radio-button :value="9">
            <template #default>
              <img src="../../../../assets/camera/window-item-9.png" class="grid" alt="" />
            </template>
          </el-radio-button>
          <el-radio-button :value="16">
            <template #default>
              <img src="../../../../assets/camera/window-item-16.png" class="grid" alt="" />
            </template>
          </el-radio-button>
          <el-radio-button :value="25">
            <template #default>
              <img src="../../../../assets/camera/window-item-25.png" class="grid" alt="" />
            </template>
          </el-radio-button>
          <el-radio-button :value="36">
            <template #default>
              <img src="../../../../assets/camera/window-item-36.png" class="grid" alt="" />
            </template>
          </el-radio-button>
        </el-radio-group>
      </el-scrollbar>
      <el-select v-model="streamTypeAct" placeholder="请选择码流类型" style="width: 150px; margin-left: 15px">
        <el-option :value="0" label="高清(主码流)"></el-option>
        <el-option :value="1" label="流畅(子码流)"></el-option>
      </el-select>
      <el-button class="camera_btn" @click="playAll">
        <el-icon size="18">
          <VideoPlay />
        </el-icon>
      </el-button>
      <el-button class="camera_btn" :disabled="closeBtn !== 0" @click="closeVideoAll">
        <el-icon size="18">
          <SwitchButton />
        </el-icon>
      </el-button>
      <el-button class="camera_btn" @click="openIntercom">
        <el-icon size="18">
          <Mic />
        </el-icon>
      </el-button>
      <el-button class="camera_btn">
        <el-icon size="18">
          <FullScreen />
        </el-icon>
      </el-button>
      <el-button type="danger" circle class="close_video_page" @click="closeVideoAll">
        <el-icon size="16"><CloseBold /></el-icon>
      </el-button>
    </div>
    <div class="cell-player">
      <div v-for="(v, i) in videoNodeIdList" v-show="i < cellCount" :key="i" class="camera_window"
        :class="cellClass(i + 1)">
        <VuePlayer :ref="(el) => (videoRefs[i] = el)" :videoData="videoData[videoNodeIdList[i]]"
          @close="removeVideo" />
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.full_screen {
  height: calc(100vh - 72px) !important;
}
.disable{
  width: 0!important;
  min-width: 0!important;
  flex: none!important;
}
.close_video_page{
  margin-left: 8px;
}
.cell {
  min-width: 500px;
  display: flex;
  flex-direction: column;

  .cell-tool {
    display: flex;
    padding: 5px 7px;
    position: relative;
    overflow: hidden;
  }

  .cell-player {
    position: relative;
    flex: 1;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;

    .cell-player-1 {
      width: 100%;
      box-sizing: border-box;
    }

    .cell-player-2 {
      width: 50%;
      box-sizing: border-box;
    }

    .cell-player-4 {
      width: 50%;
      height: 50% !important;
      box-sizing: border-box;
    }

    .cell-player-6-1 {
      width: 66.66%;
      height: 66.66% !important;
      box-sizing: border-box;
    }

    .cell-player-6-2 {
      width: 33.33%;
      height: 33.33% !important;
      box-sizing: border-box;
      display: flex;
      flex-direction: column;
    }

    .cell-player-6-position {
      width: 33.33%;
      height: 33.33% !important;
      box-sizing: border-box;
      display: flex;
      position: absolute;
      right: 0;
      top: 33.33%;
      flex-direction: column;
    }

    .cell-player-6-2-cell {
      width: 100%;
      height: 50% !important;
      box-sizing: border-box;
    }

    .cell-player-6 {
      width: 33.33%;
      height: 33.33% !important;
      box-sizing: border-box;
    }

    .cell-player-9 {
      width: 33.33%;
      height: 33.33% !important;
      box-sizing: border-box;
    }

    .cell-player-16 {
      width: 25%;
      height: 25% !important;
      box-sizing: border-box;
    }

    .cell-player-25 {
      width: 20%;
      height: 20% !important;
      box-sizing: border-box;
    }

    .cell-player-36 {
      width: 16.666%;
      height: 16.666% !important;
      box-sizing: border-box;
    }
  }
}

.camera_btn {
  padding: 8px;
  border-radius: 5px;
  margin-left: 5px;
}

.grid {
  width: 20px;
  height: 20px;
}

[class^='cell-player-'] {
  position: relative;
}

.camera_window {
  position: relative;
  background-color: #1279b1;
}

::v-deep(.grid-group) {
  flex-wrap: nowrap;
  //width: 40%;
  //overflow: hidden;
}

::v-deep(.grid-group label > span) {
  padding: 4px 8px !important;
}
</style>

<style>
/**[class^= "cell-player-"]:hover .video_close{
  opacity: 1;
  pointer-events: auto;
}*/
</style>
